
#include "ttds/ttds_interrupt_service.h"

static ttds_cjobq_t g_jobq_isr;

static int isr_thread( void *p )
{
    int32_t t0;
    int32_t diff;
    t0 = ttds_cothread_sys_tick_get_ms();
    while (1)
    {
        ttds_cothread_yeild();
        diff = ttds_cothread_sys_tick_get_ms() - t0;
        if (diff){
            t0 = ttds_cothread_sys_tick_get_ms();
        }
        ttds_cjobq_poll( &g_jobq_isr, diff, 0);
    }
    return 0;
}

ttds_cjobq_t *ttds_interrupt_service_get_jobq(void)
{
    return &g_jobq_isr;
}

void ttds_interrupt_service_init(int stack_size)
{
    ttds_cjobq_init( &g_jobq_isr );
    ttds_threadpool_run( isr_thread, 0, stack_size, "isr" );
}

static void __ttds_cosem_give_job( ttds_cjob_t *j)
{
    ttds_cosem_give( (ttds_cosem_t*)j->args, 1 );
}

void ttds_cosem_give_isr( ttds_cosem_t *p_sem )
{
    ttds_cjobq_add( &g_jobq_isr, __ttds_cosem_give_job, p_sem, NULL );
}

static int g_isr_net;
void ttds_interrupt_service_enter(void)
{
    g_isr_net++;
}
int ttds_interrupt_service_net(void)
{
    return g_isr_net;
}

void ttds_interrupt_service_leave(void)
{
    g_isr_net--;
}
